<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客服机器人</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        /* CSS样式与上一版基本一致，只是移除了api-selector相关的样式 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            background-color: #f4f4f8;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .chat-container {
            width: 90%;
            max-width: 700px;
            height: 90vh;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #6e8efb, #a777e3);
            color: white;
            padding: 15px 20px;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }

        .header-title-group {
            display: flex;
            align-items: center;
            font-size: 1.2em;
        }

        .manage-btn {
            font-size: 0.7em;
            color: white;
            background-color: rgba(255, 255, 255, 0.2);
            padding: 6px 12px;
            border-radius: 5px;
            text-decoration: none;
            margin-left: 15px;
            transition: background-color 0.3s;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .manage-btn:hover {
            background-color: rgba(255, 255, 255, 0.4);
        }

        .scene-selector {
            font-size: 0.8em;
        }

        .scene-selector label {
            margin-right: 5px;
        }

        .scene-selector select {
            border-radius: 5px;
            border: none;
            padding: 5px;
            background-color: rgba(255, 255, 255, 0.2);
            color: white;
        }

        .scene-selector select option {
            color: #333;
        }

        .chat-box {
            flex-grow: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        /* ... 其他 message, input-area 等样式保持不变 ... */
        .message {
            margin-bottom: 15px;
            display: flex;
            max-width: 90%;
        }

        .message .content {
            padding: 10px 15px;
            border-radius: 18px;
            line-height: 1.6;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }

        .user-message {
            align-self: flex-end;
        }

        .user-message .content {
            background-color: #007bff;
            color: white;
            border-bottom-right-radius: 4px;
        }

        .bot-message {
            align-self: flex-start;
        }

        .bot-message .content {
            background-color: #e9e9eb;
            color: #333;
            border-bottom-left-radius: 4px;
        }

        .input-area {
            display: flex;
            padding: 15px;
            border-top: 1px solid #ddd;
            background: #f9f9f9;
            flex-shrink: 0;
        }

        #userInput {
            flex-grow: 1;
            border: 1px solid #ccc;
            border-radius: 20px;
            padding: 10px 15px;
            font-size: 1em;
            outline: none;
            transition: border-color 0.3s;
            resize: none;
        }

        #sendBtn {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 50%;
            width: 45px;
            height: 45px;
            margin-left: 10px;
            cursor: pointer;
            font-size: 1.2em;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>

<div class="chat-container">

    <div class="chat-header">
        <div class="header-title-group">
            <span>智能客服</span>
            <a href="{{ url_for('manage_knowledge') }}" class="manage-btn">管理知识</a>
        </div>
        <div class="scene-selector">
            <label for="scene">服务场景:</label>
            <select id="scene">
                <option value="general">通用</option>
                <option value="laptop" selected>笔记本</option>
                <option value="keyboard">键盘</option>
                <option value="mouse">鼠标</option>
            </select>
        </div>
    </div>

    <div class="chat-box" id="chatBox">
        <div class="message bot-message">
            <div class="content">您好！请选择一个服务场景，然后向我提问吧。</div>
        </div>
    </div>

    <div class="input-area">
        <input type="text" id="userInput" placeholder="请输入您的问题...">
        <button id="sendBtn">➤</button>
    </div>

</div>

<script>
    const chatBox = document.getElementById('chatBox');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    const sceneSelector = document.getElementById('scene');
    let conversationHistory = [];
    let sessionId = null;
    let eventSource = null;

    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
            const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    function initializeSession() {
        sessionId = sessionStorage.getItem('chatbot_session_id');
        if (!sessionId) {
            sessionId = generateUUID();
            sessionStorage.setItem('chatbot_session_id', sessionId);
        }
    }

    async function sendMessage() {
        const userText = userInput.value.trim();
        if (userText === '') return;

        if (eventSource) {
            eventSource.close();
        }

        userInput.disabled = true;
        sendBtn.disabled = true;

        displayMessage(userText, 'user');
        conversationHistory.push({role: 'user', content: userText});
        userInput.value = '';

        const botMessageDiv = createEmptyBotMessage();
        const botContentDiv = botMessageDiv.querySelector('.content');
        let fullReply = "";

        const params = new URLSearchParams({
            scene: sceneSelector.value,
            session_id: sessionId,
            history: encodeURIComponent(JSON.stringify(conversationHistory))
        });
        const url = `/stream_chat?${params.toString()}`;

        eventSource = new EventSource(url);

        eventSource.onmessage = function (event) {
            const data = JSON.parse(event.data);
            if (data.content) {
                fullReply += data.content;
                botContentDiv.innerHTML = marked.parse(fullReply);
                chatBox.scrollTop = chatBox.scrollHeight;
            }
        };

        eventSource.addEventListener('end', function (event) {
            eventSource.close();
            conversationHistory.push({role: 'assistant', content: fullReply});
            userInput.disabled = false;
            sendBtn.disabled = false;
            userInput.focus();
        });

        eventSource.onerror = function (err) {
            console.error("EventSource failed:", err);
            botContentDiv.innerHTML += "<br><strong style='color:red;'>连接中断或发生错误。</strong>";
            eventSource.close();
            userInput.disabled = false;
            sendBtn.disabled = false;
            userInput.focus();
        };
    }

    function createEmptyBotMessage() {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', 'bot-message');
        const contentDiv = document.createElement('div');
        contentDiv.classList.add('content');
        contentDiv.innerHTML = "▍";
        messageDiv.appendChild(contentDiv);
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
        return messageDiv;
    }

    function displayMessage(text, sender) {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', `${sender}-message`);
        const contentDiv = document.createElement('div');
        contentDiv.classList.add('content');
        if (sender === 'bot') {
            contentDiv.innerHTML = marked.parse(text);
        } else {
            contentDiv.textContent = text;
        }
        messageDiv.appendChild(contentDiv);
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    function clearChat() {
        conversationHistory = [];
        chatBox.innerHTML = '';
        displayMessage(`您好！已切换场景，请问有什么可以帮您？`, 'bot');
    }

    sceneSelector.addEventListener('change', clearChat);
    sendBtn.addEventListener('click', sendMessage);
    userInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            sendMessage();
        }
    });

    document.addEventListener('DOMContentLoaded', initializeSession);
</script>
</body>
</html>